import os
import datetime
import time
import sys 
from fabric.context_managers import *
from fabric.contrib.console import confirm
from fabric.colors import *
from fabric.api  import *

#远程服务器信息
#env.hosts=['192.168.1.190']
#env.hosts=['118.31.184.204']
#env.port='22'
#env.user='root'
#env.password="Qwe21"
#env.password="task-pre-server-01"
env.remote_dir='/usr/local'

tomcat_versions={'192-168-1-190':'8.5.23','118-31-184-204':'8.5.20','106-15-138-157':'8.5.20'}

def upload_and_backup(package_name,local_path,remote_path):
  remote_package_fullname="%s/%s" %(remote_path,package_name)
  local_package_fullname="%s/%s" %(local_path,package_name)
  #备份
  try:
    run("cp %s %s" %(remote_package_fullname,remote_package_fullname +".bak"))
    run("rm -f %s" %remote_package_fullname)
  except:
    print('<----------未备份，远程包不存在-------------->')
  #上传
  put(local_package_fullname,remote_path)
def publish_service_pms():
  package_name='xing-service-wechat-pms.war'
  local_path="E:/work/src/xing-pms/services/xing-service-wechat-pms/target"
  print(env.hosts)
  if len(env.hosts)==0:
    print('找不到host!')
    return
  
  print(tomcat_versions[env.hosts[0].replace(".","-")])
  tomcat_version=tomcat_versions[env.hosts[0].replace(".","-")]
  remote_path="%s/tomcat/apache-tomcat-%s/webapps" %(env.remote_dir,tomcat_version)
  
  upload_and_backup(package_name, local_path, remote_path)
  reload_tomcat(remote_path)

def publish_service_ui():

  package_name='service-wechat-ui.jar'
  local_path="E:/work/src/xing-pms/services/xing-service-wechat-ui/target"
  remote_path="%s/services" %env.remote_dir

  run ("mkdir -p %s" %remote_path)
  #上传备份
  upload_and_backup(package_name,local_path,remote_path)
  #重启服务
  reload_jar(package_name,remote_path)
def reload_jar(package_name,package_path):
  #重启服务 需要转到jar目录再执行
  with cd(package_path):
    try:
      #把tomcat进程也杀死了 ？？？
      run("ps aux | grep %s | xargs kill -9 && sleep 5" %package_name)
    except:
      print ("结束服务失败！")
    run("set -m; java -jar %s > log.file 2>&1 &" %package_name)
def reload_tomcat(tomcat_webapps_path):
  with cd (tomcat_webapps_path):
    try:
      run("ps -ef |grep tomcat |grep -v grep   |awk -F\" \" '{print $2}' |xargs kill -9 && sleep 5")
    except:
      print("未找到tomcat进程")
    run("set -m; ../bin/startup.sh")
def startup_tomcat():
  tomcat_version=tomcat_versions[env.hosts[0].replace(".","-")]
  remote_path="%s/tomcat/apache-tomcat-%s/webapps" %(env.remote_dir,tomcat_version)
  with cd(remote_path):
    run("set -m; ../bin/startup.sh")
def down_tomcat():
  tomcat_version=tomcat_versions[env.hosts[0].replace(".","-")]
  remote_path="%s/tomcat/apache-tomcat-%s/webapps" %(env.remote_dir,tomcat_version)
  with cd (remote_path):
    run("ps -ef |grep tomcat |grep -v grep   |awk -F\" \" '{print $2}' |xargs kill -9 && sleep 5")
    #run("../bin/shutdown.sh")